#include "reader.h"
#include "writer.h"
#include "request.h"
#include "stringbuffer.h"

namespace pack {

Reader::Reader(net::IBuffer* buffer) {
	this->buffer = buffer;

	is_good = true;
}

Reader::~Reader() {

}

Reader::operator bool() {
	return is_good;
}

Reader& Reader::operator>>(uint32_t& v) {
	uint32_t temp = 0;

	if(is_good) {
		is_good = (buffer->Read((char*)&temp, sizeof(uint32_t)) == sizeof(uint32_t));
	}

	if(is_good) {
		v = temp;
	}
	return *this;
}

Reader& Reader::operator>>(std::string& v) {
	uint32_t size = 0;
	char* str = NULL;

	this->operator>>(size);
	if(size == 0) {
		is_good = false;
		return *this;
	}

	str = new char[size + 1];
	str[size] = 0;

	is_good = (buffer->Read(str, size) == size);

	if(is_good) {
		v = str;
	}

	delete[] str;
	return *this;
}

Reader& Reader::operator>>(std::list<uint32_t>& v) {
	size_t size = 0;

	this->operator>>(size);

	for(size_t i = 0; i < size; i++) {
		uint32_t temp;

		this->operator>>(temp);

		if(is_good) {
			v.push_back(temp);
		}
		else {
			v.clear();
			break;
		}
	}
	return *this;
}

Reader& Reader::operator>>(std::list<std::string>& v) {
	size_t size = 0;

	this->operator>>(size);

	for(size_t i = 0; i < size; i++) {
		std::string temp;

		this->operator>>(temp);

		if(is_good) {
			v.push_back(temp);
		}
		else {
			v.clear();
			break;
		}
	}
	return *this;
}

}
